# -*- coding: utf-8 -*-
# @Date    : 2024/2/5
# @Author  : zouy
# @Email: 874112501@qq.com
import os
import subprocess
from functools import partial

subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')

import requests
from lxml import etree
import execjs

DIR_PATH = os.path.dirname(os.path.abspath(__file__))


headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "no-cache",
    "Pragma": "no-cache",
    "Proxy-Connection": "keep-alive",
    "Referer": "http://www.fangdi.com.cn/index.html",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
cookies = {
    # "FSSBBIl1UgzbN7N80S": "GkMvOPOR2zBCVsQEB.kvrp8c09MaBt9Z4z5v2kzr4OF3jgytrI0CcP_CLbjb7aVH",
    "www.fangdi.com_http_ic": "www.fangdi.com.cn_80_RS",
    # "FSSBBIl1UgzbN7N80T": "4XQnYs.FW_Xmfaz6PD8YA3Rx1mZj6pwxCz1eI7_4lZ5RLbw_KslOYk3h1a3wTBpJP5x5.vhgimumrTaVMAUJgrBWaQy5_GMTE74VTNzdCmViki0eYwajPW7AGFKvVbgOvfxgn8IzQedPz_fsXY46XQAcEaO_IcySZDrjaqAFG3PHcR8AOjRd9ujI3sHLpPVOPWjWqpKn2fvsKW2lOMCs2fuBHyTBXZz93X4wtriC8l8eYYbaA3oP5AxLasmnWfK15309X9vVSdbuwE64nXt8QWQ5XvaajzXt8wy_oMCH9OmfQGBmvwku0cgzu7xOioFuNqZOW6YFZUb1HOJxVgzi1CjlK"
}

request_session = requests.session()
request_session.headers.update(headers)
request_session.cookies.update(cookies)
url = "http://www.fangdi.com.cn/index.html"


# http://www.fangdi.com.cn/4QbVtADbnLVIc/c.FxJzG50F.dfe1675.js
def get_code():
    response = request_session.get(url)
    print(response)  # 202
    cookies['FSSBBIl1UgzbN7N80S'] = response.cookies['FSSBBIl1UgzbN7N80S']
    request_session.cookies.update(cookies)
    html = etree.HTML(response.text)
    meta_content = html.xpath('//meta[2]/@content')[0]
    js_code = html.xpath('//script[2]/text()')[0]

    return meta_content, js_code


meta_content, js_code = get_code()



with open(os.path.join(DIR_PATH, "房地产.js"), 'r', encoding='utf-8') as js_file:
    js_text = js_file.read()
    js_text = js_text.replace('meta_content', meta_content)
    js_text = js_text.replace("'js_code'", js_code)

js = execjs.compile(js_text)
f80t = js.call('main')
print(f"FSSBBIl1UgzbN7N80T长度：{len(f80t)}  值：【{f80t}】") # 217
cookies['FSSBBIl1UgzbN7N80T'] = f80t
request_session.cookies.update(cookies)

# with open('./fdcc.js', 'w', encoding='utf-8') as f:
#     f.write(js_text)

# path = '/service/index/getProclamation.action'
path = '/service/index/getSecondHouse.action'
get_msg_url = "http://www.fangdi.com.cn" + path
url = js.call('getUrl', path)
print(url)
response = request_session.get(url)
response.encoding = 'utf-8'
print(response.text)
print(response)
